package gwtI18nEditor.datamodel;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class Directory implements DirectoryEntry {
	
	public static final Directory ROOT = new Directory(null, null, ".");

	private       File               file;
			final Directory			 parent;
	private final String             name;
	private final List<Directory>    subdirectories;
	private final List<MessageFile>  files;
	
	private boolean empty  = true;
	private String  prefix = "";
	private int     incompletes = 0;
	
	public Directory(File file, Directory parent, String name) {
		this.file           = file;
		this.parent         = parent;
		this.name           = name;
		this.subdirectories = new ArrayList<Directory>();
		this.files          = new ArrayList<MessageFile>();
	}
	
	public void clear() {
		subdirectories.clear();
		files.clear();
		empty = true;
		prefix = "";
		incompletes = 0;
		// TODO: (maybe) propagate incompletes to parents.
		// technically not needed, as we only ever clear ROOT.
	}

	public String getName() {
		return prefix+name;
	}
	
	public File getFile() {
		return file;
	}
	
	public void setFile(File file) {
		this.file = file;
	}

	private void setNamePrefix(String prefix) {
		this.prefix = prefix;
	}

	public List<Directory> getSubdirectories() {
		return subdirectories;
	}
	
	public Directory addSubdirectory(File file, String name) {
		Directory result = new Directory(file, this, name);
		subdirectories.add(result);
		return result;
	}

	public List<MessageFile> getFiles() {
		return files;
	}
	
	public void addFile(MessageFile messageFile) {
		files.add(messageFile);
		Directory dir = this;
		while (dir!=null) {
			dir.empty = false;
			dir = dir.parent;
		}
	}
	
	public boolean isEmpty() {
		return empty;
	}
	
	public static Directory reROOT() {
		Directory next = ROOT;
		String name = "";
		while (true) {
			boolean first = true;
			Directory current = next;
			if (!current.getFiles().isEmpty()) {
				current.setNamePrefix(name);
				return current;
			}
			for (Directory dir: current.getSubdirectories()) {
				if (!dir.isEmpty()) {
					if (first) {
						next = dir;
						first = false;
					} else {
						current.setNamePrefix(name);
						return current;
					}
				}
			}
			if (first) return ROOT;
			name+=current.name+"/";
		}
	}
	
	@Override
	public String toString() {
		return getName();
	}

	@Override
	public boolean isDirectory() {
		return true;
	}

	@Override
	public boolean needsAttention() {
		return incompletes > 0;
	}

	public void addIncomplete() {
		incompletes++;
	}

	public void removeIncomplete() {
		incompletes--;
	}

	public void check(Locale... locales) {
		for (Directory directory: subdirectories) directory.check(locales);
		for (MessageFile msgFile: files) msgFile.check(locales);
	}
}
